package com.mijie.homi.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class GrammarLoader {

	private Map<NatureNode,NatureNode> dict = new HashMap<NatureNode,NatureNode>();
	
	/**		
	 * 	    v--ques
	 * 		|   |--adj
	 * 	    |
	 * 		|---u--adj
	 * 		    |--adv--adj
	 *      
	 *      n--adv--adj
	 * 		|   |--adv--adj
	 *      |   |--u--adv--adj
	 *      |
	 *      |---v    	
	 *			  			
	 */
	public void init() throws IOException{
		InputStream is = getClass().getClassLoader().getResourceAsStream("com/mijie/homi/test/grammar.txt");
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(isr);
		String line = null;
		String[] elements = null;
		NatureNode prefix = null;
		NatureNode prev = null;
		while((line=br.readLine())!=null){
			if(line.trim().isEmpty()) continue;
			prefix = null;
			prev = null;
			elements = line.split("\\+");
			for(String e : elements){
				if(prefix==null){
					prefix = new NatureNode(e);
					prev = dict.get(prefix);//root
					if(prev==null){
						prev = new NatureNode(e);
						dict.put(prefix, prev);
					}
				}else{
					NatureNode child = prev.findChild(e);
					if(child!=null){
						prev = child;
						continue;
					}
					
					NatureNode curr = new NatureNode(e);
					prev.addChild(curr);
					NatureNode tmp = prev;
					curr.prev(tmp);
					prev = curr;
				}//closing outermost if
			}//closing foreach
			prev.isLeaf(true);
		}//closing while
	}
	
	public NatureNode getTree(String prefix){
		return dict.get(new NatureNode(prefix));
	}
	
	public boolean legal(String ... natures){
		int index = 0;
		NatureNode node = getTree(natures[index++]);
		if(node==null) return false;
		String next = null;
		for(;;){
			next = natures[index];
			node = node.findChild(next);
			if(node!=null) index++; else return false;
			if(index==natures.length){
				return node.isLeaf();
			}
		}
	}
	
	public static void main(String[] args) throws IOException{
		GrammarLoader grammar = new GrammarLoader();
		grammar.init();
		String[] natures = {"adv","v"};
		System.out.println(grammar.legal(natures));
	}
}
